package com.baiyinet.ui.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.R;
import com.baiyinet.biz.AdInfo;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.ApiResult;
import com.baiyinet.rest.AppInfo;
import com.baiyinet.rest.ChannelInfo;
import com.baiyinet.rest.Link;
import com.baiyinet.rest.LinkStructure;
import com.baiyinet.ui.BaseToolbarFragment;
import com.baiyinet.ui.general.GeneralActivity_;
import com.baiyinet.util.DialogUtils;
import com.baiyinet.util.DoubleClickExitDetector;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.Utils;
import com.baiyinet.util.webview.WebViewTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.JsonObject;
import com.umeng.analytics.MobclickAgent;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.jpush.android.api.JPushInterface;
import myandroid.library.util.ApplicationHelper;
import rx.Subscriber;
import timber.log.Timber;

import static com.baiyinet.Constants.AD_SHOW_SECOND;

/**
 * @author J.Huang
 * @version 1.0
 * @since 16/12/5
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(MainActivity.class)
@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    @Inject
    SharedPreferences mSharedPref;
    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    DoubleClickExitDetector mDoubleClickExitDetector;

    @StringRes(R.string.network_disabled)
    String strNetworkDisabled;
    @StringRes(R.string.api_error)
    String strApiError;

    @ViewById(R.id.view_loading_indicator)
    SpinKitView loadingIndicator;

    @ViewById(R.id.tab_layout)
    CommonTabLayout mTabLayout;

    @ViewById(R.id.activity_main_layout_ad)
    RelativeLayout mAdLayout;
    @ViewById(R.id.activity_main_layout_backgroud)
    LinearLayout mMainLayout;

    @ViewById(R.id.open_ad_tv_num)
    TextView mNumText;
    @ViewById(R.id.open_ad_layout_backgroud)
    RelativeLayout mOpenAdLayout;

    private ArrayList<Fragment> mFragmentList = new ArrayList<>();
    private AppInfo mAppInfo;

    private int[] mIconUnselectIds = {
            R.drawable.tab_ic_home_unselected,
            R.drawable.tab_ic_shop_unselected,
            R.drawable.tab_ic_union_unselected,
            R.drawable.tab_ic_demand_unselected,
            R.drawable.tab_ic_more_unselected
    };

    private int[] mIconSelectIds = {
            R.drawable.tab_ic_home_selected,
            R.drawable.tab_ic_shop_selected,
            R.drawable.tab_ic_union_selected,
            R.drawable.tab_ic_demand_selected,
            R.drawable.tab_ic_more_selected
    };

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    Subscriber<LinkStructure> mLinkSubscriber;
    Subscriber<AppInfo> mAppInfoSubscriber;

    private final int MSG_CODE_AD_COUNT_DOWN = 111;
    private final int MSG_CODE_TO_NEW_WEBVIEW = 222;
    private final int MSG_CODE_HIDE_AD = 333;

    int initTabIndex = 0;
    private String mIntentAdUrl;
    private String mAdUrl;

    private int mAdCountDownSecond = AD_SHOW_SECOND;

    private NormalDialog mPushMsgPermissionDialog;
    private NormalDialog mDownloadPermissionDialog;
    private boolean mainType = true;

    @AfterInject
    void initDI() {
        initTabIndex = getIntent().getIntExtra("tabIndex", 0);
        mIntentAdUrl = getIntent().getStringExtra("adUrl");

        Injector.initMainActivityComponent().inject(this);
    }

    @AfterViews
    void init() {
        showPushMsgPermissionDialog();

        ApplicationHelper.getInstance().addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);   //统计时长

        if (!TextUtils.isEmpty(mCurrentUser.getBackActionTarget()) && mainType) {
            if (mCurrentUser.getBackActionTarget().equals(((BaseToolbarFragment)getCurrentFragment()).getCurrentPageName())) {
                if (mCurrentUser.getBackActionReload()) {
                    if (Utils.Network.isNetworkAvailable()) {
                        ((BaseToolbarFragment)getCurrentFragment()).reloadWebView();
                    } else {
                        Utils.UI.showToastShort(strNetworkDisabled);
                    }
                }
            }
        }

        // 清空回退信息
        mCurrentUser.setBackAction("", false);

        // 检查应用信息
        getAppInfo();

    }

    @Override
    public void onPause() {
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);

        mCurrentUser.setAppLastUsedTime(SystemClock.elapsedRealtime());

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mPushMsgPermissionDialog != null) {
            mPushMsgPermissionDialog.superDismiss();
            mPushMsgPermissionDialog = null;
        }
        if (mDownloadPermissionDialog != null) {
            mDownloadPermissionDialog.superDismiss();
            mDownloadPermissionDialog = null;
        }
        if (mMsgHandler != null) {
            mMsgHandler.removeCallbacksAndMessages(null);
        }

        ApplicationHelper.getInstance().removeActivity(this);

        super.onDestroy();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // app资源被系统回收后，activity保存了一份fragment的状态，有可能导致白屏
        // 注释父类方法，以完全重建fragment
//        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        if (mDoubleClickExitDetector.click()) {
            Utils.App.clearCache(this);
            ApplicationHelper.getInstance().exit();
            super.onBackPressed();
        }
    }

    private void showPushMsgPermissionDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {

                BaseAnimatorSet bas_in = new FadeEnter();
                BaseAnimatorSet bas_out = new FadeExit();
                mPushMsgPermissionDialog = new NormalDialog(this);

                mPushMsgPermissionDialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("信息推送功能无法正常使用\n请在\"设置\"中开启电话状态权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .showAnim(bas_in)
                        .dismissAnim(bas_out)
                        .show();

                mPushMsgPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(MainActivity.this);
                        mPushMsgPermissionDialog.dismiss();
                    }
                });
            }
        }
    }

    private boolean showDownloadPermissionDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                BaseAnimatorSet bas_in = new FadeEnter();
                BaseAnimatorSet bas_out = new FadeExit();
                mDownloadPermissionDialog = new NormalDialog(this);

                mDownloadPermissionDialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("应用自动升级功能无法使用!\n请在\"设置\"中开启存储卡权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .showAnim(bas_in)
                        .dismissAnim(bas_out)
                        .show();

                mDownloadPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(MainActivity.this);
                        mDownloadPermissionDialog.dismiss();
                    }
                });

                return true;
            }
        }
        return false;
    }

    public void checkWebView() {
        for (Fragment fragment : mFragmentList) {
            if (fragment instanceof BaseToolbarFragment) {
                ((BaseToolbarFragment) fragment).checkWebView();
            }
        }
    }

    public void refreshCurrentTabIndex() {
        mCurrentUser.setCurrentTab(mTabLayout.getCurrentTab());
    }

    public CurrentUser getCurrentUser() {
        return mCurrentUser;
    }

    public ApiHelper getApiHelper() {
        return mApiHelper;
    }

    private void getAppInfo() {
        if (!Utils.Network.isNetworkAvailable()) {
            isNetworkConnectionFailed(true);
            Utils.UI.showToastShort(strNetworkDisabled);
            return;
        }

        mAppInfoSubscriber = new AppInfoSubscriber();
        mApiHelper.getAppInfo(mAppInfoSubscriber);
    }

    private void checkUpdate() {
        long lastCheck = mSharedPref.getLong("checkUpdateTime", 0);
        long now = System.currentTimeMillis();
        if (now - lastCheck > 3600 * 2 * 1000) {
            SharedPreferences.Editor editor = mSharedPref.edit();
            editor.putLong("checkUpdateTime", now);
            editor.apply();

            if (mCurrentUser.getLatestAppVersion() > Utils.App.getAppVersionCode()) {

                if (!showDownloadPermissionDialog()) {
                    DialogUtils.showUpdateDialog(this, mCurrentUser.getAppDownloadUrl(), mSharedPref);
                }
            }
        }
    }

    private void checkUserLoginStatus() {
        if (mCurrentUser.hasMultiLoggedIn()) {
            DialogUtils.showUserMultiLoginDialog(this, mCurrentUser);
        } else {
            if (!mCurrentUser.hasLoggedIn()) {
                Utils.UI.showToastShort("用户登陆状态过期");
                mCurrentUser.logout();
                IntentUtils.toLogin(this);
            }
        }
    }

    private void setTabLayoutData(LinkStructure linkStructure) {
        if (linkStructure == null || linkStructure.Home.size() < 1) {
            return;
        }

        mFragmentList.clear();
        mTabEntities.clear();

        if (BuildConfig.FLAVOR.startsWith("yongshenglianmeng")) {
            mApiHelper.readAll(new ReadAllSubscriber(linkStructure));
            mainType = false;
        }else {
            initTabData(linkStructure, null);
        }
    }

    private void initTabData(LinkStructure linkStructure, ChannelInfo channelInfo) {
        boolean toolbarVisible;
        String url;

        for (int i = 0; i < linkStructure.Home.size(); i++) {

            Link link = linkStructure.Home.get(i);

            Uri uri = Uri.parse(link.Url);
            String pageMode = uri.getQueryParameter("PageMode");

            toolbarVisible = pageMode == null || !"fullscreen".equals(pageMode.toLowerCase());

            if (link.Url.startsWith("http")) {
                url = link.Url;
            } else {
                url = BuildConfig.ENDPOINT + link.Url;
            }

            String addLinkName = "";
            String addLinkUrl = "";
            String addLinkCode = uri.getQueryParameter("AddLink");
            if (addLinkCode != null) {
                for (Link addLink : linkStructure.AddLink) {
                    if (addLink.Code.equals(addLinkCode)) {
                        addLinkName = addLink.Name;
                        addLinkUrl = addLink.Url;
                        break;
                    }
                }
            }

            PageStatus pageStatus = new PageStatus(url, toolbarVisible, addLinkName, addLinkUrl, mCurrentUser.getToolbarBgColor());
            pageStatus.code = link.Code;

            Fragment fragment;
            switch (i) {
                case 0:
                    if (channelInfo == null) {
                        fragment = WebViewFragment1_.builder().pageStatus(pageStatus).build();
                    }else {
                        fragment = HomeFragment_.builder().channelInfo(channelInfo).pageStatus(pageStatus).build();
                    }
                    break;
                case 1:
                    fragment = WebViewFragment2_.builder().pageStatus(pageStatus).build();
                    break;
                case 2:
                    fragment = WebViewFragment3_.builder().pageStatus(pageStatus).build();
                    break;
                case 3:
                    fragment = WebViewFragment4_.builder().pageStatus(pageStatus).build();
                    break;
                case 4:
                    fragment = WebViewFragment5_.builder().pageStatus(pageStatus).build();
                    break;
                case 5:
                    fragment = WebViewFragment6_.builder().pageStatus(pageStatus).build();
                    break;
                default:
                    Timber.e("Too many Home Home!");
                    fragment = null;
                    break;
            }

            if (fragment != null) {
                mFragmentList.add(fragment);
            }

            switch (link.Code) {
                case "Home":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_home_selected,
                            R.drawable.tab_ic_home_unselected));
                    break;
                case "Product":
                case "Catalog":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_shop_selected,
                            R.drawable.tab_ic_shop_unselected));
                    break;
                case "Union":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_union_selected,
                            R.drawable.tab_ic_union_unselected));
                    break;
                case "Demand":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_demand_selected,
                            R.drawable.tab_ic_demand_unselected));
                    break;
                case "Best":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_best_selected,
                            R.drawable.tab_ic_best_unselected));
                    break;
                case "More":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_more_selected,
                            R.drawable.tab_ic_more_unselected));
                    break;
                case "Cart":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_cart_selected,
                            R.drawable.tab_ic_cart_unselected));
                    break;
                case "User":
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_user_selected,
                            R.drawable.tab_ic_user_unselected));
                    break;
                default:
                    mTabEntities.add(new TabEntity(link.Name,
                            R.drawable.tab_ic_more_selected,
                            R.drawable.tab_ic_more_unselected));
                    break;
            }
        }

        mTabLayout.setTabData(mTabEntities, this, R.id.layout_content, mFragmentList);

        if (initTabIndex < 0 || initTabIndex >= mFragmentList.size()) {
            initTabIndex = 0;
        }

        mTabLayout.setCurrentTab(initTabIndex);


    }

    public void setLastValidUrl(String url) {
        if (mainType) {
            ((BaseToolbarFragment)getCurrentFragment()).lastValidUrl = url;
        }

    }

    public Fragment getCurrentFragment() {
        int index = mTabLayout.getCurrentTab();
        switch (index) {
            case 0:
                if (mainType) {
                    return (WebViewFragment1_) mFragmentList.get(index);
                }else {
                    return (HomeFragment_) mFragmentList.get(index);
                }
            case 1:
                return (WebViewFragment2_) mFragmentList.get(index);
            case 2:
                return (WebViewFragment3_) mFragmentList.get(index);
            case 3:
                return (WebViewFragment4_) mFragmentList.get(index);
            case 4:
                return (WebViewFragment5_) mFragmentList.get(index);
            default:
                return (WebViewFragment6_) mFragmentList.get(index);
        }

    }

    public void isNetworkConnectionFailed(boolean isFailed) {
        if (!mainType) return;

        if (((BaseToolbarFragment)getCurrentFragment()).networkFailedView != null) {
            if (isFailed) {
                // 展示错误页面
                ((BaseToolbarFragment)getCurrentFragment()).networkFailedView.setVisibility(View.VISIBLE);
            } else {
                ((BaseToolbarFragment)getCurrentFragment()).networkFailedView.setVisibility(View.GONE);
            }
        }
    }

    public String getLastValidUrl() {
        if (mainType) {
            return ((BaseToolbarFragment)getCurrentFragment()).lastValidUrl;
        }else {
            return "";
        }

    }

    public void loadUrl(String url) {
        if (!mainType) return;
        ((BaseToolbarFragment)getCurrentFragment()).loadUrl(url);
    }

    private List<String> mDownloadedImgList = null;

    public void setDownloadedImgList(List<String> list) {
        if (mDownloadedImgList != null) {
            mDownloadedImgList.clear();
        }
        mDownloadedImgList = list;
    }

    public List<String> getDownloadedImgList() {
        return mDownloadedImgList;
    }

    @Click(R.id.open_ad_layout_jump)
    void hideAd() {
        mMsgHandler.removeMessages(MSG_CODE_AD_COUNT_DOWN);
        mAdLayout.setVisibility(View.GONE);
        mMainLayout.setVisibility(View.VISIBLE);
    }

    private void initBaiduAd() {
//        AdBaiduSplash splash = new AdBaiduSplash(this, "4588225", mOpenAdLayout);
//        splash.setAdListener(new AdBaiduSplashListener() {
//            @Override
//            public void onAdLoaded() {
//
//            }
//
//            @Override
//            public void onAdFailed() {
//
//            }
//
//            @Override
//            public void onAdClose() {
//
//            }
//
//            @Override
//            public void onAdClick() {
//
//            }
//        });

//        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
    }

    private void initAdInfo(AdInfo adInfo) {
        mMainLayout.setVisibility(View.INVISIBLE);
        mAdLayout.setVisibility(View.VISIBLE);
        mNumText.setText(String.valueOf(AD_SHOW_SECOND));

        ArrayList<AdInfo.AdDetail> data = adInfo.getData();
        int total = adInfo.getData().size();
        String imgUrl;
        if (total > 1) {
            Random random = new Random();
            int randomIndex = random.nextInt(data.size());
            mAdUrl = data.get(randomIndex).getUrl();
            imgUrl = data.get(randomIndex).getImage();
        } else {
            mAdUrl = data.get(0).getUrl();
            imgUrl = data.get(0).getImage();
        }

        if (!mAdUrl.startsWith("http") && !mAdUrl.startsWith("#")) {
            mAdUrl = BuildConfig.ENDPOINT + mAdUrl;
        }

        if (!imgUrl.startsWith("#") && !imgUrl.startsWith("http")) {
            imgUrl = BuildConfig.ENDPOINT + imgUrl;
        }

        ImageView imageView = new ImageView(this);

        if (!mAdUrl.startsWith("#")) {
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mMsgHandler.sendEmptyMessage(MSG_CODE_TO_NEW_WEBVIEW);
                }
            });
        }

        imageView.setScaleType(ImageView.ScaleType.CENTER);

        DisplayMetrics dm = getResources().getDisplayMetrics();

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                dm.widthPixels,
                dm.heightPixels);

        mOpenAdLayout.addView(imageView, params);

        Glide
                .with(this)
                .load(imgUrl)
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .centerCrop()
                .into(new GlideDrawableImageViewTarget(imageView) {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                        super.onResourceReady(resource, animation);
                        mAdCountDownSecond = AD_SHOW_SECOND;
                        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
                    }
                });
    }

    void checkOpeningAd() {
        if ("Show".equals(mAppInfo.ShowStartAd)) {
            mApiHelper.startAd(new StartAdSubscriber());
        }
    }

    private Handler mMsgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CODE_AD_COUNT_DOWN:
                    mAdCountDownSecond--;
                    if (mAdCountDownSecond > 0) {
                        mNumText.setText(String.valueOf(mAdCountDownSecond));
                        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
                    } else {
                        hideAd();
                    }
                    break;
                case MSG_CODE_TO_NEW_WEBVIEW:
                    hideAd();
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, GeneralActivity_.class);
                    PageStatus pageStatus = new PageStatus(mAdUrl, true, true, mCurrentUser.getToolbarBgColor());
                    intent.putExtra(PageStatus.EXTRA_NAME, Parcels.wrap(pageStatus));
                    startActivity(intent);
                    break;
                case MSG_CODE_HIDE_AD:
                    hideAd();
                    break;
                default:
                    break;
            }
        }
    };

    @Click(R.id.open_ad_tv_num)
    void skipAd() {
        mMsgHandler.sendEmptyMessage(MSG_CODE_HIDE_AD);
    }

    @Background(delay = 3000)
    public void delayToFinishApp() {
        finish();
    }

    private int mConnectionCount = 0;

    private class LinkSubscriber extends Subscriber<LinkStructure> {
        @Override
        public void onCompleted() {
            if (!TextUtils.isEmpty(mIntentAdUrl)) {
                PageStatus pageStatus = new PageStatus(mIntentAdUrl, true, true, mCurrentUser.getToolbarBgColor());
                IntentUtils.toNewGeneralActivity(MainActivity.this, pageStatus);
                mIntentAdUrl = "";
            }
        }

        @Override
        public void onError(Throwable e) {
//            mCurrentUser.logout();
//            IntentUtils.toLogin(MainActivity.this);

            if (mConnectionCount < 3) {
                mApiHelper.getLink(new LinkSubscriber());
                mConnectionCount ++;
            }else {
                Utils.UI.showToastShort(strApiError);
                mConnectionCount = 0;
                delayToFinishApp();
            }

        }

        @Override
        public void onNext(LinkStructure linkStructure) {
            checkUpdate();
            checkUserLoginStatus();

            if (!linkStructure.toString().equals(mCurrentUser.getLink())) {
                mCurrentUser.setLink(linkStructure.toString());
                mCurrentUser.setAddLinkList(linkStructure.AddLink);
                setTabLayoutData(linkStructure);
            }
        }
    }

    private class AppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
            // get link info for TabLayout
            mLinkSubscriber = new LinkSubscriber();
            mApiHelper.getLink(mLinkSubscriber);
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
        }

        @Override
        public void onNext(AppInfo appInfo) {
            mCurrentUser.setAppInfo(appInfo);
            mAppInfo = appInfo;

            long currentTime = SystemClock.elapsedRealtime();
            try {
                if ((currentTime - mCurrentUser.getAppLastUsedTime()) > Integer.valueOf(appInfo.StartAdReshowTime) * 60 * 1000) {
                    checkOpeningAd();
                }
            } catch (Exception e) {
            }
        }
    }

    private class StartAdSubscriber extends Subscriber<AdInfo> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
        }

        @Override
        public void onNext(AdInfo adInfo) {
            if (adInfo != null) {

                // 测试数据
//                adInfo.Total = 1;
//                AdInfo.AdDetail adDetail = new AdInfo.AdDetail();
//                adDetail.setUrl("#");
//                adDetail.setImage("http://fzmy.app3.baiyinet.com/App_Attachment/UnAuth/SDP_StartAdImage/1.jpg");
//                ArrayList<AdInfo.AdDetail> list = new ArrayList<>();
//                list.add(adDetail);
//                adInfo.setData(list);

                if (adInfo.getData() != null && adInfo.getTotal() > 0) {
                    initAdInfo(adInfo);
                } else {
                    initBaiduAd();
                }
            }
        }
    }

    private class ReadAllSubscriber extends Subscriber<ChannelInfo> {

        private LinkStructure mLinkStructure;

        public ReadAllSubscriber(LinkStructure linkStructure) {
            mLinkStructure = linkStructure;
        }

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(ChannelInfo channelInfo) {
            if (channelInfo != null && channelInfo.ChannelList != null && channelInfo.ChannelList.size() > 0) {
                if (!channelInfo.toString().equals(mCurrentUser.getChannelInfo())) {
                    mCurrentUser.setChannelInfo(channelInfo.toString());
                    initTabData(mLinkStructure, channelInfo);
                }
            }
        }
    }

}
